package chat

import (
	"golang.org/x/net/websocket"
	"io"
	"log"
)

type Client struct {
	server *Server
	name   string
	conn   *websocket.Conn
	chMsg  chan *Message
	doneCh chan bool
	chErr  chan error
}

func NewClient(conn *websocket.Conn, srv *Server, name string) *Client {

	return &Client{
		server: srv,
		name:   name,
		conn:   conn,
		chMsg:  make(chan *Message),
		doneCh: make(chan bool),
		chErr:  make(chan error),
	}
}

//发消息
func (c *Client) Write(m *Message) {
	c.conn.Write([]byte(m.String()))
}

//读取消息
func (c *Client) ListenRead() {
	var msg Message
	for {
		err := websocket.JSON.Receive(c.conn, &msg)
		if err != nil {
			if err == io.EOF {
				log.Println("for循环退出了。。")
				c.doneCh <- true
				return
			} else {
				return
				//c.chErr <- err
			}
		} else {
			c.chMsg <- &msg
		}

	}

}

//监听，读和写,
func (c *Client) Listen() {

	//读关闭之后，回收写的gorouting
	go c.ListenWrite()
	c.ListenRead()

}

func (c *Client) ListenWrite() {

	for {
		select {

		case <-c.doneCh:
			log.Println("io断开")
			c.server.Del(c)
			c.conn.Close()
			goto over
		case msg := <-c.chMsg:
			//判断是群发还是点对点发送
			switch msg.To {
			case "all":
				log.Println("send to all")
				c.server.SendAll(msg)
			default:
				c.server.SendToOne(msg.To, msg)
			}
		case err := <-c.chErr:
			log.Println("解析错误", err.Error())
			//c.server.Del(c)
			//c.conn.Close()
			//return
		}
	}
over:
}
